<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="打印证书" />

      <!-- 内容区域 -->
      <view class="content-area">
        <!-- 表单区域 -->
        <view class="form-section">
          <!-- 资质证书选择 -->
          <view class="form-item">
            <view class="form-label">
              <text class="required">*</text>
              <text>资质证书</text>
            </view>
            <view class="form-input" @click="selectCertificate">
              <text class="input-text" :class="{ placeholder: !selectedCertificate }">
                {{
                  selectedCertificate
                    ? `${selectedCertificate.event_name} ${selectedCertificate.item_name} 第${selectedCertificate.rank}名`
                    : '暂无可选择的证书'
                }}
              </text>
              <text class="arrow">></text>
            </view>
          </view>

          <!-- 选择款式 -->
          <view class="form-item">
            <view class="form-label">
              <text class="required">*</text>
              <text>选择款式</text>
            </view>
            <view class="form-input" @click="selectStyle">
              <text class="input-text" :class="{ placeholder: !selectedStyle }">
                {{ selectedStyle ? selectedStyle.name : '请选择' }}
              </text>
              <text class="arrow">></text>
            </view>
          </view>

          <!-- 领取赛站 -->
          <view class="form-item">
            <view class="form-label">
              <text class="required">*</text>
              <text>领取赛站</text>
            </view>
            <view class="form-input" @click="selectStation">
              <text class="input-text" :class="{ placeholder: !selectedStation }">
                {{ selectedStation ? selectedStation.name : '暂无可选择的赛站' }}
              </text>
              <text class="arrow">></text>
            </view>
          </view>
        </view>

        <!-- 说明文字 -->
        <view class="description">
          <text class="description-text">说明: 下单后仅限当天比赛现场签到处领取</text>
        </view>
      </view>

      <!-- 底部支付区域 -->
      <view class="bottom-payment">
        <view class="total-price">
          <text class="total-label">总计:</text>
          <text class="total-amount">¥{{ totalPrice }}</text>
        </view>
        <button class="pay-btn" :disabled="!canPay" @click="goToPay"> 去支付 </button>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import { useRequest } from '@/api'
  import { onLoad } from '@dcloudio/uni-app'

  // API接口
  const {
    API_CERTIFICATE_INDEX_POST,
    API_CERTIFICATE_STYLE_POST,
    API_CERTIFICATE_STATION_POST,
    API_CERTIFICATE_PRINT_ORDER_POST,
    API_CERTIFICATE_PRINT_ORDER_PAY_POST
  } = useRequest()

  // 使用store获取导航高度
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)

  // 响应式数据
  const selectedCertificate = ref(null)
  const selectedStyle = ref(null)
  const selectedStation = ref(null)
  const isLoading = ref(false)

  // 保存选择项的ID，按照API字段名
  const course_id = ref(null) // 赛程ID
  const certificatestyle_id = ref(null) // 款式ID
  const station_id = ref(null) // 赛站ID

  // 从API获取的数据
  const certificateList = ref([])
  const styleList = ref([])
  const stationList = ref([])

  // 计算总价
  const totalPrice = ref(0)

  // 检查是否可以支付
  const canPay = computed(() => {
    return selectedCertificate.value && selectedStyle.value && selectedStation.value
  })

  // 选择证书
  const selectCertificate = () => {
    if (certificateList.value.length === 0) {
      uni.showToast({
        title: '暂无证书数据',
        icon: 'none'
      })
      return
    }

    if (selectedCertificate.value) {
      // 如果已选择证书，显示取消选择选项
      uni.showActionSheet({
        itemList: ['取消选择'],
        success: () => {
          selectedCertificate.value = null
          course_id.value = null
          uni.showToast({
            title: '已取消选择',
            icon: 'none'
          })
        }
      })
    } else {
      // 显示证书选择列表
      const certificateNames = certificateList.value.map(
        (cert) => `${cert.event_name} ${cert.item_name} 第${cert.rank}名`
      )

      uni.showActionSheet({
        itemList: certificateNames,
        success: (res) => {
          selectedCertificate.value = certificateList.value[res.tapIndex]
          course_id.value = selectedCertificate.value.course_id
          uni.showToast({
            title: `已选择证书`,
            icon: 'success'
          })
        }
      })
    }
  }

  // 选择款式
  const selectStyle = () => {
    if (styleList.value.length === 0) {
      uni.showToast({
        title: '暂无款式数据',
        icon: 'none'
      })
      return
    }

    if (selectedStyle.value) {
      // 如果已选择款式，显示取消选择选项
      uni.showActionSheet({
        itemList: ['取消选择'],
        success: () => {
          selectedStyle.value = null
          certificatestyle_id.value = null
          totalPrice.value = 0
          uni.showToast({
            title: '已取消选择',
            icon: 'none'
          })
        }
      })
    } else {
      // 显示款式选择列表
      uni.showActionSheet({
        itemList: styleList.value.map((style) => `${style.name} ¥${style.price}`),
        success: (res) => {
          selectedStyle.value = styleList.value[res.tapIndex]
          certificatestyle_id.value = selectedStyle.value.id
          totalPrice.value = selectedStyle.value.price
          uni.showToast({
            title: `已选择${selectedStyle.value.name}`,
            icon: 'success'
          })
        }
      })
    }
  }

  // 选择领取赛站
  const selectStation = () => {
    if (stationList.value.length === 0) {
      uni.showToast({
        title: '暂无赛站数据',
        icon: 'none'
      })
      return
    }

    if (selectedStation.value) {
      // 如果已选择赛站，显示取消选择选项
      uni.showActionSheet({
        itemList: ['取消选择'],
        success: () => {
          selectedStation.value = null
          station_id.value = null
          uni.showToast({
            title: '已取消选择',
            icon: 'none'
          })
        }
      })
    } else {
      // 显示赛站选择列表
      uni.showActionSheet({
        itemList: stationList.value.map((station) => station.name),
        success: (res) => {
          selectedStation.value = stationList.value[res.tapIndex]
          station_id.value = selectedStation.value.id
          uni.showToast({
            title: `已选择${selectedStation.value.name}`,
            icon: 'success'
          })
        }
      })
    }
  }

  // 去支付
  const goToPay = async () => {
    if (!canPay.value) {
      uni.showToast({
        title: '请完善所有必填信息',
        icon: 'none'
      })
      return
    }

    try {
      uni.showLoading({
        title: '创建订单中...'
      })
      const params = {
        course_id: course_id.value,
        certificatestyle_id: certificatestyle_id.value,
        station_id: station_id.value
      }
      const res = await API_CERTIFICATE_PRINT_ORDER_POST(params)
      if (res.code === 1) {
        const res2 = await API_CERTIFICATE_PRINT_ORDER_PAY_POST({ id: res.data.id })
        if (res2.code === 1) {
          uni.hideLoading()
          uni.showToast({
            title: '创建订单成功',
            icon: 'success'
          })
          uni.navigateBack()
        }
      }
    } catch (error) {
      uni.hideLoading()
      console.error('创建订单失败:', error)
      uni.showToast({
        title: '创建订单失败，请重试',
        icon: 'none'
      })
    }
  }

  // 页面滚动处理
  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }
  // 获取证书列表
  const getCertificateList = async () => {
    try {
      const params = {
        page: 1,
        page_size: 999
      }
      const res = await API_CERTIFICATE_INDEX_POST(params)
      if (res && res.code === 1) {
        certificateList.value = res.data.data || []
        console.log('证书列表:', res.data.data)
      }
    } catch (error) {
      console.error('获取证书列表失败:', error)
    }
  }

  // 获取款式列表
  const getStyleList = async () => {
    try {
      const params = {
        page: 1,
        page_size: 999
      }
      const res = await API_CERTIFICATE_STYLE_POST(params)
      if (res && res.code === 1) {
        styleList.value = res.data.data || []
        console.log('款式列表:', res.data.data)
      }
    } catch (error) {
      console.error('获取款式列表失败:', error)
    }
  }

  // 获取赛站列表
  const getStationList = async () => {
    try {
      const params = {
        page: 1,
        page_size: 999
      }
      const res = await API_CERTIFICATE_STATION_POST(params)
      if (res && res.code === 1) {
        stationList.value = res.data.data || []
        console.log('赛站列表:', res.data.data)
      }
    } catch (error) {
      console.error('获取赛站列表失败:', error)
    }
  }

  // 初始化数据
  const initData = async () => {
    await Promise.all([getCertificateList(), getStyleList(), getStationList()])
  }
  // 页面加载
  onLoad((options) => {
    initData()
  })

  // 页面显示
  onMounted(() => {
    // 页面初始化逻辑
  })
</script>

<style lang="scss" scoped>
  .content-area {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
  }

  .form-section {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 16px;
  }

  .form-item {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .form-label {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      font-size: 16px;
      font-weight: 600;
      color: #333;

      .required {
        color: #ff4757;
        margin-right: 4px;
      }
    }

    .form-input {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #e9ecef;
      transition: all 0.3s ease;

      &:active {
        background: #e9ecef;
        border-color: #213165;
      }

      .input-text {
        flex: 1;
        font-size: 16px;
        color: #333;

        &.placeholder {
          color: #999;
        }
      }

      .arrow {
        font-size: 18px;
        color: #999;
        font-weight: 300;
      }
    }
  }

  .description {
    padding: 16px 20px;
    background: #fff;
    border-radius: 12px;
    margin-bottom: 100px; // 为底部支付区域留出空间

    .description-text {
      font-size: 14px;
      color: #ff4757;
      line-height: 1.5;
    }
  }

  .bottom-payment {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 1px solid #e8e8e8;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 100;

    .total-price {
      display: flex;
      align-items: center;
      gap: 8px;

      .total-label {
        font-size: 16px;
        color: #333;
      }

      .total-amount {
        font-size: 20px;
        font-weight: 600;
        color: #ff4757;
      }
    }

    .pay-btn {
      background: #213165;
      color: #fff;
      border: none;
      border-radius: 24px;
      padding: 6px 32px;
      font-size: 16px;
      font-weight: 600;
      transition: all 0.3s ease;
      &:active {
        transform: scale(0.98);
        background: #1a2a52;
      }

      &:disabled {
        background: #ccc;
        color: #999;
        transform: none;
      }
    }
  }
</style>
